package com.own.demo.lwf.threadTest.ExecutorsTest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @version v1.0
 * @Description:测试创建定长线程池
 * @Author 李文峰
 * @Date 2023/4/30 0030 17:59
 */
public class TestNewFixedThreadPool {
    public static void main(String[] args) {
        // 创建工作线程数为3的线程池，每当提交一个任务就创建一个线程，直到达到线程池的最大数量，这时线程池数量不再变化，当线程发生错误结束时，线程池会补充一个新的线程
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 6; i++) {
            final int index = i;
            fixedThreadPool.execute(()->{
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "index:" + index);
            });
        }
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("4秒后...");
        // 关闭线程池后已提交的任务仍然会执行完
        fixedThreadPool.shutdown();
    }
}
